package com.gyg.threadPool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 线程池异常处理
 */
@Slf4j
public class PoolExceptionHand {
    public static void main(String[] args) {
        //handMethod1();
        handMethod2();
    }

    /**
     * 使用try-catch主动处理异常
     */
    public static void handMethod1() {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        pool.execute(() -> {
            log.info("Thread Run...");
            //主动处理异常
            try {
                int i = 1 / 0;
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        log.info("end...");
    }

    /**
     * 使用future接收异常
     */
    public static void handMethod2() {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        Future<?> future = pool.submit(() -> {
            log.info("Thread Run...");
            int i = 1 / 0;
        });
        try {
            log.info("result：" +future.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        log.info("end...");
    }
}
